<template>
  <div class="ability-analysis-view">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>我的能力分析报告</span>
          <el-select
            v-model="selectedSubject"
            placeholder="选择科目"
            size="small"
            style="width: 120px; margin-left: 12px"
            @change="fetchAnalysisData"
          >
            <el-option
              v-for="subject in AllSubjects"
              :key="subject"
              :label="subject"
              :value="subject"
            />
          </el-select>
          <el-text v-if="analysisData" size="small" style="margin-left: auto" type="info"
            >报告生成时间:
            {{ analysisData.analysisTime }}
          </el-text>
        </div>
      </template>
      <div v-if="loading" v-loading="loading" style="height: 400px" />
      <div v-else-if="analysisData">
        <v-chart :option="chartOption" autoresize class="chart" />
      </div>
      <el-empty v-else description="暂无分析数据，请先进行练习" />
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref } from 'vue'
import { apiClient, handleErrorAndRedirect } from '@/api'
import VChart from 'vue-echarts'
import { AllSubjects } from '@/api/utils.ts'

const loading = ref(true)
const analysisData = ref<any>(null)
const chartOption = ref({})
const selectedSubject = ref('语文')

const fetchAnalysisData = async () => {
  loading.value = true
  analysisData.value = null
  try {
    const response = await apiClient.get('/student/me/ability-analysis', {
      params: { subject: selectedSubject.value },
    })
    if (!response.data?.masteryMap || Object.keys(response.data.masteryMap).length === 0) {
      analysisData.value = null
    } else {
      analysisData.value = response.data
      updateChart()
    }
  } catch (error) {
    handleErrorAndRedirect(error, '获取能力分析数据失败')
  } finally {
    loading.value = false
  }
}

const updateChart = () => {
  if (!analysisData.value?.masteryMap) return
  const masteryData = Object.entries(analysisData.value.masteryMap).map(([name, value]) => ({
    name,
    value: (value as number) * 100,
  }))

  chartOption.value = {
    tooltip: { trigger: 'item', formatter: '{b} : {c}%' },
    radar: {
      indicator: masteryData.map((item) => ({ name: item.name, max: 100 })),
    },
    series: [
      {
        name: '知识点掌握度',
        type: 'radar',
        data: [
          {
            value: masteryData.map((item) => Number(item.value.toFixed(2))),
            name: '掌握度',
          },
        ],
      },
    ],
  }
}

onMounted(fetchAnalysisData)
</script>

<style scoped>
.ability-analysis-view {
  padding: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 12px;
}

.chart {
  height: 500px;
}
</style>
